import { onMounted, onUnmounted, onActivated, onDeactivated, ref, computed } from "vue"


// 传入el
function getScrollHook(el) {
  let item = window
  const isReachButton = ref(false)
  const scrollHeight = ref()
  const scrollTop = ref()
  const clientHeight = ref()
  let lastScrollTop = computed(() => scrollTop.value)
  console.log(lastScrollTop.value)


  const scrollFn = () => {
    if (item === window) {
      // document的整体高度
      scrollHeight.value = document.documentElement.scrollHeight
      // document顶部距离客户窗口顶部距离
      scrollTop.value = document.documentElement.scrollTop
      // 客户窗口的高度
      clientHeight.value = document.documentElement.clientHeight
    } else {
      // document的整体高度
      scrollHeight.value = item.scrollHeight
      // document顶部距离客户窗口顶部距离
      scrollTop.value = item.scrollTop
      // 客户窗口的高度
      clientHeight.value = item.clientHeight
    }


    if (scrollTop.value + clientHeight.value >= scrollHeight.value) {
      isReachButton.value = true
    }
  }

  onMounted(() => {
    // 如果存在el，就监听el的内部。如果没有el，就监听浏览器窗口
    if (el) {
      item = el.value
    }
    item.addEventListener("scroll", scrollFn)
  })

  onUnmounted(() => {
    item.removeEventListener("scroll", scrollFn)
  })

  onActivated(() => {
    item.addEventListener("scroll", scrollFn)
    item.scrollTo({
      top: lastScrollTop.value
    })
  })

  onDeactivated(() => {
    item.removeEventListener("scroll", scrollFn)
  })

  return { isReachButton, scrollHeight, scrollTop, clientHeight }
}

export default getScrollHook